<template>
	<view style="padding: 40rpx;">
		<view style="padding: 20rpx; margin: 80rpx 0; background-color: #fff; box-shadow: 0 2rpx 10rpx rgba(0,0,0,.1); border-radius: 10rpx;">
			<uni-forms ref="form" :modelValue="form" :rules="rules" validateTrigger='blur'>
				<uni-forms-item name="password" required>
					<uni-easyinput type = "password" prefixIcon="locked" v-model="form.password" placeholder="请输入原密码密码" />
				</uni-forms-item>
				<uni-forms-item name="newPassword" required>
					<uni-easyinput type = "password" prefixIcon="locked" v-model="form.newPassword" placeholder="请输入新密码" />
				</uni-forms-item>
				<uni-forms-item name="confirmPassword" required>
					<uni-easyinput type = "password" prefixIcon="locked" v-model="form.confirmPassword" placeholder="请确认新密码" />
				</uni-forms-item>
				<uni-forms-item>
					<button @click="change()" style="background-color: #b9cfff; border-color: #b9cfff; height: 70rpx; line-height: 70rpx;">确认修改</button>
				</uni-forms-item>
			</uni-forms>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			const validatePassword = (rule, value, callback) => {
			      if (value === '') {
			        callback(new Error('请确认密码'))
			      } else if (value !== this.user.newPassword) {
			        callback(new Error('确认密码错误'))
			      } else {
			        callback()
			      }
			    }
			return {
				form: {
					role: 'USER'
				},
				rules: {
					password: {
						// username 字段的校验规则
						rules:[
							// 校验 username 不能为空
							{
								required: true,
								errorMessage: '请输入新密码',
							}
						],
					},
					newPassword: {
						// username 字段的校验规则
						rules:[
							// 校验 username 不能为空
							{
								required: true,
								errorMessage: '请输入新密码',
							},
							// 对username字段进行长度验证
							{
								minLength: 6,
								maxLength: 10,
								errorMessage: '账号长度在 {minLength} 到 {maxLength} 个字符',
							}
						],
					},
					confirmPassword: {
						rules:[
							{
								validator: validatePassword,
								required: true,
								errorMessage: '请确认新密码',
							}
						],
					}
				}
			}
		},
		methods: {
			change() {
				this.$refs.form.validate().then(res=>{//表单校验
					this.$request.put('/updatePassword', this.form).then(res => {
						if (res.code === '200') {
							uni.showToast({
								icon: 'success',
								title: '修改成功',
								//登陆成功过后，token便存在了localStorage里面，所有数据请求都会带上token
							})
							//异步
							uni.removeStorageSync('xm-user', res.data)
							setTimeout(() => {
								// 跳转登录页面
								uni.switchTab({
								url: '/pages/index/index'
							})
							}, 500)
							// 跳转主页
						} 
						else {
							// 提示消息
							uni.showToast({
								icon: 'error',
								title: res.msg
							})
						}
					})
				}).catch(err =>{
					console.log('表单错误信息：', err);
				})
			}
		}
	}
</script>

<style>

</style>
